package com.cqz.services;

import com.cqz.mapper.BookInfoMapper;
import com.cqz.mapper.BookTagMapper;
import com.cqz.dao.BookInfo;
import com.cqz.dao.BookTag;
import com.cqz.tools.Tools;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * bookService服务层
 */
@Service("bookService")
public class BookService {
    @Autowired
    private SqlSession sqlSession;

    @Autowired
    private BookInfoMapper bookInfoMapper;

    /**
     * 添加书籍信息以及书籍标签
     * @param bookInfo
     * @param tags
     * @return
     */
    public boolean addBookAndTag(BookInfo bookInfo, String[] tags) {
       int i=bookInfoMapper.insertSelective(bookInfo);
       if(i!=1) return false;
       BookInfo bookInfo1=bookInfoMapper.selectByBook(bookInfo);
       if(bookInfo1==null) return false;
       else{
           int bid=bookInfo1.getBid();
           BookTagMapper bookTagMapper=sqlSession.getMapper(BookTagMapper.class);
           //插入非空的标签
           for(int j=0;j<6;j++){
               if(Tools.isNull(tags[j]))continue;
               bookTagMapper.insertSelective(new BookTag(bid,tags[j]));
           }
       }
       return true;
    }

    /**
     * 查询所有书名包含searchContent的书籍信息
     * @param searchContent 查询内容
     * @return
     */
    public List<BookInfo> searchBookAndEdit(String searchContent) {
        BookInfo bookInfo=new BookInfo();
        bookInfo.setBname(searchContent);
        return sqlSession.selectList("selectByBookPartten",bookInfo);
    }

    /**
     * 根据图书ID更新书籍信息(选择性更新)
     * @param bookInfo
     * @return
     */
    public boolean updateBookInfo(BookInfo bookInfo) {
        int i=bookInfoMapper.updateByPrimaryKeyWithBLOBs(bookInfo);
        if(i<=0) return false;
        else return true;
    }

    /**
     * 根据书籍编号bid得到书籍信息
     * @param bid
     * @return
     */
    public BookInfo getBookById(int bid) {
        return bookInfoMapper.selectByPrimaryKey(bid);
    }
}
